<script setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { dayjs, ElMessage } from 'element-plus'
import ElementPlus from 'element-plus'
import { getActivationapi, endDropDownapi, getEndUserdeviceapi, getActivationlike, editequipmentStatus, delActivation, InventoryFile, delInventory, adminResetPassword, editaccountNonLocked } from '../../api/api'
import data from "@/untils/address/states.json"
import { readFile } from "../../untils/importfile/importfile"
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
import { Decrypt, Encrypt } from '../../untils/passjs/security'
onMounted(() => {
    getActivation()
})
// 定义的头部输入框的数据
let topdata = ref({
    generatetime: '',
    expirationStatus: null
    // equipmentName: "",
    // equipmentNumber: '',
    // // equipmentType: '',
    // userId:null,
    // onlineStatus: null,
    // equipmentStatus: null,
    // timevalue: "",
    // time: ""
})
// 表格数据
let tableData = ref([])
async function getActivation() {
    let data = await getActivationapi(page.value, pageSize.value)
    if (data.code == 200) {
        total.value = data.total
        tableData.value = data.rows
    }
}
// 渲染状态的显示
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}

//    // 删除
let inventoryStatus = ref(null)
let activationId = ref(0)
let equipmentId = ref(0)
const dialogVisible = ref(false)
function del(val) {
    console.log(val);
    activationId.value = val.activationId
    equipmentId.value = val.equipmentId
    dialogVisible.value = true
}
async function yesdel() {
    dialogVisible.value = false
    console.log(activationId.value);
    console.log(equipmentId.value);
    let requestData = {
        activationId: activationId.value,
        equipmentId: equipmentId.value
    }
    let res = await delActivation(requestData)
    console.log("del", res);
    if (res.code == 200) {
        ElMessage.success(res.msg)
        getActivation()
    }
}
// 遮罩层
let dialogFormVisible = ref(false)
// 定义 是添加还是编辑的字符串
let changeType = ref("")
//  传递参数
let formlist = reactive({})
function add() {
    // tableData.value = []
    // Object.assign(formlist, {
    //     // 用户名、昵称、密码、邮箱、手机号、性别(0,1)、区域(国家/洲(省))、地址(非必填)、用户等级(1-5)
    //     equipmentName: "",
    //     equipmentNumber: "",
    //     equipmentModel: "",
    //     equipmentType: null,
    //     inventoryStatus: null,
    //     type: "新增",
    // })
    // console.log(formlist);
    //  //点击添加按钮
    dialogFormVisible.value = true
    console.log("新增操作");
    changeType.value = 'add'
}
function edit(index, row) {
    // Object.assign(formlist, {
    //     equipmentId: row.equipmentId,
    //     equipmentName: row.equipmentName,
    //     equipmentNumber: row.equipmentNumber,
    //     equipmentModel: row.equipmentModel,
    //     type: "修改",
    // })
    console.log(index, row);
    //  //点击编辑按钮
    //  //把row数据赋值给formlist
    // formlist = row
    // console.log(formlist);
    //  //让changeType 标识 为update
    changeType.value = "update"
    //  //让dialogFormVisible显示
    dialogFormVisible.value = true
}
//     // 子传父的事件，关闭遮罩层
function closechange() {
    dialogFormVisible.value = false
    getActivation()
}
function formatDate(dateStr) {
    const date = new Date(dateStr);

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以+1
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
async function adminlike() {
    isSearching.value = true
    console.log("模糊查询操作", topdata.value);
    if (topdata.value.generatetime.length > 0) {
        topdata.value.generatetime[0] = formatDate(topdata.value.generatetime[0])
        topdata.value.generatetime[1] = formatDate(topdata.value.generatetime[1])
    }
    // if (topdata.value.expiretime.length > 0) {
    //     topdata.value.expiretime[0] = formatDate(topdata.value.expiretime[0])
    //     topdata.value.expiretime[1] = formatDate(topdata.value.expiretime[1])
    // }
    console.log(topdata.value);
    let res = await getActivationlike(topdata.value.generatetime[0], topdata.value.generatetime[1],topdata.value.expirationStatus, page.value, pageSize.value)
    console.log(res, "like查询");
    if (res.code == 200) {
        tableData.value = res.rows
        if (res.rows.length == 0) {
            return;
        }
        total.value = res.total
    }
}
let isSearching = ref(false)
function cancel() {
    console.log("重置操作");
    isSearching.value = false
    topdata.value = {
        generatetime: '',
        expirationStatus: null
    }
    page.value = 1
    getActivation()
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    if (isSearching.value) {
        await adminlike()
    } else {
        // 否则调用普通分页API
        getActivation()
    }
}
let switchActivationDay = (activationDay) => {
    if (activationDay == 0) {
        return 'test code'
    } else if (activationDay == -1) {
        return 'Permanent'
    } else if (activationDay == -2) {
        return 'reset code'
    } else {
        return activationDay + 'day'
    }
}
const hasPermission = (permission) => {
    const permissions = JSON.parse(localStorage.getItem("userdetail"))?.auths || [];
    if (permissions[0] === '*:*:*') {
        return true; // 如果有 *:*:* 权限，直接返回 true
    }
    return permissions.includes(permission);
};
</script>

<template>
    <div class="administrator">
        <div class="administratorbas">
            <div class="top">
                <span>Inventory equipment</span>
            </div>
            <div class="cont">
                <div class="one">
                    <!-- 生成时间 -->
                    <div class="select">
                        <el-date-picker v-model="topdata.generatetime" type="datetimerange"
                            start-placeholder="generate Start date" end-placeholder="generate End date"
                            format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                    </div>
                    <!-- 过期时间
                    <div class="select">
                        <el-date-picker v-model="topdata.expiretime" type="datetimerange"
                            start-placeholder="expire Start date" end-placeholder="expire End date"
                            format="YYYY-MM-DD HH:mm:ss" date-format="YYYY/MM/DD ddd" time-format="A hh:mm:ss" />
                    </div> -->
                    <!-- 过期状态 -->
                    <div class="select">
                        <el-select style="width: 180px" placeholder="expirationStatus"
                            v-model="topdata.expirationStatus">
                            <el-option label="normal" :value="0" />
                            <el-option label="expire" :value="1" />
                        </el-select>
                    </div>
                    <el-button type="primary" @click="adminlike">query</el-button>
                    <el-button type="primary" @click="cancel">reset</el-button>
                </div>
                <div class="exp">
                    <!-- <div class="export-excel">
                        <el-button style="width: 180px" type="primary" @click="Bangding()">
                            <el-icon style="margin-right: 5px;">
                                <FolderAdd />
                            </el-icon>Bind end users
                        </el-button>
                    </div> -->
                </div>
                <div class="tab">
                    <el-table stripe :data="tableData" @selection-change="check()" style="width: 100%;" :fit="true" v-if="hasPermission('activation:equipment:query')">
                        <el-table-column width="55"></el-table-column>
                        <el-table-column property="activationCode" label="activationCode" />
                        <el-table-column property="equipmentNumber" label="equipmentCode"    />
                        <el-table-column property="activationDay" label="days">
                            <template #default="scope">
                                <span>{{ switchActivationDay(scope.row.activationDay) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="generationTime" label="generationTime" />
                        <!-- <el-table-column property="expirationTime" label="expirationTime" /> -->
                        <el-table-column property="expirationStatus" label="status">
                            <template #default="scope">
                                <span>{{ scope.row.expirationStatus == 0 ? 'normal' : 'expire' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column property="optUsername" label="operator" />
                        <el-table-column property="name" label="operate" width="300">
                            <template #default="scope">
                                <!-- <span class="more-button" @click="edit(scope.$index, scope.row)"
                                    style="cursor: pointer;" >
                                    edit
                                </span> -->
                                <span class="more-button" @click="del(scope.row)" style="cursor: pointer;" v-if="hasPermission('activation:generate:remove')">
                                    delete
                                </span>
                                <!-- 添加“更多”按钮及下拉菜单 -->
                                <!-- <el-dropdown style="cursor: pointer;" v-show="scope.row.optStatus">
                                    <span class="more-button">
                                        more
                                        <el-icon class="el-icon--right"><arrow-down /></el-icon>
                                    </span>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="viewDetails">activation code</el-dropdown-item>
                                            <el-dropdown-item command="viewDetails"
                                                @click="returnHandler(scope.row)">return</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
    </el-dropdown> -->
                                <!-- <el-dialog v-model="passwordVisible" title="reset password" width="500"
                                    modal-class="custom-modal" @close="passwordVisible = false">
                                    <span>please enter {{ currentUser.username }} new password:</span>
                                    <br>
                                    <el-form :model="resetForm" :rules="rulesobj" ref="resetFormRef">
                                        <el-form-item label="" prop="newpass">
                                            <el-input v-model="resetForm.newpass" type="password" maxlength="16"
                                                minlength="8" auto-complete="off" placeholder="password"></el-input>
                                        </el-form-item>
                                    </el-form>
                                    <template #footer>
                                        <div class="dialog-footer">
                                            <el-button @click="passwordVisible = false">cancel</el-button>
                                            <el-button type="primary" @click="reactpass(scope.row)">sure</el-button>
                                        </div>
                                    </template>
                                </el-dialog> -->
                            </template>

                        </el-table-column>
                    </el-table>
                    <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                        <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                            style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                    </div>
                    <el-dialog v-model="dialogVisible" title="delete" width="500">
                        <span>Are you sure you want to delete it</span>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible = false">cancel</el-button>
                                <el-button type="primary" @click="yesdel()">
                                    sure
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>

            </div>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.administrator {
    padding: 15px;
    background-color: #eff1f4;

    .administratorbas {
        background-color: #fff;
        width: 100%;
        height: 88vh;
        border-radius: 10px 10px 0 0;

        .top {
            height: 50px;
            background-color: #f9f9f9;
            border-radius: 10px 10px 0 0;
            font-size: 20px;
            font-weight: bold;
            overflow: hidden;
            border-bottom: 1px solid #f1eded;

            span {
                display: block;
                margin: 10px 0 0 15px;
            }
        }

        .cont {
             .one {
                margin: 10px;
                display: flex;
                flex-wrap: wrap;
                gap: 12px;
                align-items: center;
                padding: 10px;
            }
            .select {
                display: flex;
                align-items: center;
            }

            .exp {
                .export-excel {
                    margin-left: 20px;
                }

            }

            .tab {
                margin-top: 20px;
                width: 100%;
                position: relative;
                min-height: 300px;

                .el-table {
                    --el-table-header-bg-color: #fafafa;
                }

                .el-switch {
                    --el-switch-on-color: #45d585;
                }

                .more-button {
                    margin-left: 8px;
                    margin-top: 3px;
                    /* 为“更多”按钮添加左边距 */
                    color: #409EFF;
                    outline: none;

                    /* Element Plus 主题色 */
                    &:hover {
                        color: #66b1ff;

                        /* 鼠标悬停时的颜色 */
                    }
                }
            }
        }
    }

    /* 如果使用 scoped，需要添加 ::v-deep */
    ::v-deep .custom-modal {
        background-color: rgba(0, 0, 0, 0.5);
        /* 设置弹窗背景颜色为半透明 */
    }

    /* 或者更精确的定位 */
    ::v-deep .custom-modal .el-overlay {
        background-color: rgba(0, 0, 0, 0.8);
    }

    .demo-datetime-picker {
        display: flex;
        width: 100%;
        padding: 0;
        flex-wrap: wrap;
        justify-content: space-around;
        align-items: stretch;
    }

    .demo-datetime-picker .block {
        padding: 30px 0;
        text-align: center;
    }

    .line {
        width: 1px;
        background-color: var(--el-border-color);
    }

    .el-switch {
        --el-switch-on-color: #45d585;
    }
}
</style>